import { memo, useState, ForwardRefRenderFunction, useImperativeHandle, forwardRef, useRef } from 'react'
import { Checkbox, Flex, Modal, Radio } from 'antd'
import { message } from '@hs-admin/utils'
import { getDataItemPolymerizeOptions } from '@/api/setting/item'
import { useImmer } from 'use-immer'
import { HsAdminSpin } from '@hs-admin/base-components'
import List from 'rc-virtual-list'

interface Props {
  onCheckPolymierize: (settingList: any[], key: number, checkList: string[]) => any
}

const PolymerizeOptions: ForwardRefRenderFunction<unknown, Props> = (props: Props, ref: any) => {
  const { onCheckPolymierize } = props
  const [isOpen, setIsOpen] = useState(false)
  const [checkList, setcheckList] = useImmer<any[]>([])
  const settingList = useRef<any[]>([])
  const key = useRef<number>(0)
  const [loading, setloading] = useState(true)

  const handleOk = async () => {
    if (checkList.length) {
      let checkIdList = checkList.filter((item) => item.checked).map((item) => item.value)
      if (checkIdList.includes('unlimited')) {
        checkIdList = checkList.filter((item) => item.value !== 'unlimited').map((item) => item.value)
      }
      if (checkIdList.length > 500) {
        message.warning('该字段聚合结果过多，请重新选择字段，否则该筛选无法生效')
        return
      }
      onCheckPolymierize(settingList.current, key.current, checkIdList).then(() => {
        handleCancel()
      })
    } else {
      handleCancel()
    }
  }
  const handleCancel = () => {
    setcheckList([])
    settingList.current = []
    key.current = 0
    setIsOpen(false)
  }
  // 选择筛选项
  const polymerizeCheckChange = (item: any, checked: boolean, index: number) => {
    if (checked) {
      if (item.value === 'unlimited') {
        setcheckList((prev) => {
          prev.forEach((ele) => {
            ele.checked = false
          })
          prev[index].checked = true
        })
      } else {
        setcheckList((prev) => {
          prev[index].checked = true
          prev[0].checked = false
        })
      }
    } else {
      setcheckList((prev) => {
        prev[index].checked = false
      })
    }
  }

  useImperativeHandle(
    ref,
    () => {
      return {
        async showModal(release_item_id: any, originSettingList: any[], originKey: number, selectedList: string[]) {
          setloading(true)
          setIsOpen(true)
          settingList.current = originSettingList
          key.current = originKey
          const item = originSettingList[originKey]
          getDataItemPolymerizeOptions({ release_item_id, column_name: item.column })
            .then((res) => {
              const list = [
                {
                  label: '全部',
                  value: 'unlimited',
                  checked: selectedList.length ? false : true
                },
                ...res.map((ele: any) => {
                  if (selectedList.includes(ele)) {
                    return {
                      label: ele,
                      value: ele,
                      checked: true
                    }
                  } else {
                    return {
                      label: ele,
                      value: ele,
                      checked: false
                    }
                  }
                })
              ]
              setcheckList(list)
              if (list.length > 501) {
                onCheckPolymierize(settingList.current, key.current, list)
              }
            })
            .finally(() => {
              setloading(false)
            })
        }
      }
    },
    [setcheckList]
  )

  return (
    <Modal title="选择筛选项" open={isOpen} onOk={handleOk} onCancel={handleCancel} width={400}>
      {loading && <HsAdminSpin />}
      {checkList.length <= 501 && (
        <List data={checkList} height={500} itemHeight={30} itemKey="value">
          {(item, index) => (
            <Flex key={item.value}>
              {item.value === 'unlimited' ? (
                <Radio checked={item.checked} onChange={(e) => polymerizeCheckChange(item, e.target.checked, index)}>
                  {item.label}
                </Radio>
              ) : (
                <Checkbox checked={item.checked} onChange={(e) => polymerizeCheckChange(item, e.target.checked, index)}>
                  {item.label}
                </Checkbox>
              )}
            </Flex>
          )}
        </List>
      )}
      {checkList.length > 501 && <h1>该字段聚合结果过多，请重新选择字段，否则该筛选无法生效</h1>}
    </Modal>
  )
}

export default memo(forwardRef(PolymerizeOptions))
